package top.kaoshanji.p3ch11b;

import top.kaoshanji.p3ch11b.support.Printer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * 代码清单-p3ch11b-358页a：使用信号量管理资源的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/4 16:58
 */
public class PrinterManager {

    // 信号量
    private final Semaphore semaphore;

    // 可用的资源：打印机集合
    private final List<Printer> printerList = new ArrayList<>(); // 随书源码是 printers

    public PrinterManager(Collection<? extends Printer> printers) {
        this.printerList.addAll(printers);
        this.semaphore = new Semaphore(this.printerList.size(), true);
    }

    public Printer acquirePrinter() throws InterruptedException {
        semaphore.acquire();
        return getAvailablePrinter();
    }

    public void releasePrinter(Printer printer) {
        putBackPrinter(printer);
        semaphore.release();
    }

    private synchronized Printer getAvailablePrinter() {
        Printer result = printerList.get(0);
        printerList.remove(0);
        return result;
    }

    private synchronized void putBackPrinter(Printer printer) {
        printerList.add(printer);
    }

}
